// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Form,Radio,Tooltip, Button,Popconfirm, Modal, Row, Col, Input, Select, Cascader, Icon, Checkbox, Tabs, DatePicker, message } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './monthReportDetailStyle.less'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import { Grid } from 'widget/Grid/index'
import ReactEcharts from 'echarts-for-react';
import moment from 'moment';

const FormItem = Form.Item
const { RangePicker,MonthPicker } = DatePicker
const { Option } = Select;
const { TextArea } = Input;
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const monthReportDetailView = function ({ dispatch, model, form }) {
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue,validateFieldsAndScroll  } = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  let {optionData,countyList,areaList,cityList,tableData,keys,query, actionType,btnLoading} = modelObj

  const formItemLayoutPro = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
  };
  let all = optionData.xingong.concat(optionData.mianji)
  // let max1= Math.floor(Math.max.apply(null,all)+Math.max.apply(null,all)/10)
  // let max2= Math.floor(Math.max.apply(null,optionData.junjia)+Math.max.apply(null,optionData.junjia)/10)
  let length1 = Math.floor(Math.max.apply(null,all)/10).toString().length
  let length2 = Math.floor(Math.max.apply(null,optionData.junjia)/10).toString().length
  let interval1= Math.floor(Math.max.apply(null,all)/Math.pow(10,length1))*Math.pow(10,length1)/5
  let interval2= Math.floor(Math.max.apply(null,optionData.junjia)/Math.pow(10,length2))*Math.pow(10,length2)/5
  let max1= Math.floor(Math.max.apply(null,all))+interval1
  let max2= Math.floor(Math.max.apply(null,optionData.junjia))+interval2
  let option = {
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'cross',
            crossStyle: {
                color: '#9'
            }
        }
    },
    grid: {
      left: '4%',
      right: '4%',
      containLabel: true
    },
    legend: {
        data: ['新供面积（万m²）', '成交面积（万m²）', '成交均价（元/m²）'],
        bottom: 0,
    },
    xAxis: [
        {
            type: 'category',
            data: optionData.yuefen,
            axisPointer: {
                type: 'shadow'
            },
            axisLabel: {
                rotate:40
            }
        }
    ],
    yAxis: [
        {
            type: 'value',
            min: 0,
            max: max1,
            // interval: interval1,
            axisLabel: {
                formatter: '{value}'
            },
            axisTick: {
                show: false
            },
            axisLine: {
                show: false
            }
        },
        {
            type: 'value',
            min: 0,
            max: max2,
            // interval: interval2,
            axisLabel: {
                formatter: '{value}'
            },
            splitLine:{
        　　　　show:false
        　　},
            axisTick: {
                show: false
            },
            axisLine: {
              show: false
          }
        }
    ],
    series: [
        {
            name: '新供面积（万m²）',
            type: 'bar',
            data: optionData.xingong,
            itemStyle: {   
              //通常情况下：
              normal:{  
                  color: '#5b9bd5'
              },
            },
        },
        {
            name: '成交面积（万m²）',
            type: 'bar',
            data: optionData.mianji,
            itemStyle: {   
              //通常情况下：
              normal:{  
                  color: '#ed7d31'
              },
            },
        },
        {
            name: '成交均价（元/m²）',
            type: 'line',
            data: optionData.junjia,
            yAxisIndex: 1,
            itemStyle : { normal: {label : {show: true}}}
        }
    ]
  };

  const columns1 = [
    {
      title: '统计月份', dataIndex: 'month', key: 'month',
      render: function (value, item, index) {
        return item.month
      }
    },
    {
      title: '新供面积（万m²）', dataIndex: 'addAcreage', key: 'addAcreage',
      render: function (value, item, index) {
        return item.addAcreage
      }
    },
    {
      title: '成交面积（万m²）',dataIndex: 'transactionAcreage',key: 'transactionAcreage',
      render: function (value, item, index) {
        return  item.transactionAcreage
      }
    },
    {
      title: '成交均价（元/m²）', dataIndex: 'averagePrice', key: 'averagePrice',
      render: function (value, item, index) {
        return item.averagePrice
      }
    }, 
  ]
   
  // 表格配置------------开始
  const gridProps = {
    nameSpace: namespace,
    data: {
      columns: columns1
      ,//已发布的活动不能添加和删除时间段
      pageConfig:{},
      tableData: {total: '',dataSource: tableData},
      selectedRowKeys:'',
    },
    scroll: { x: '60%' },
    paginationFlag : false,
  }

  //输入框改变时
  function inputChange(e, name) {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        query: {
          ...query,
          [name]: e,
        }
      }
    })
    if(query.areaCode&&query.month&&query.cityCode&&query.transactionAcreage&&query.averagePrice){
      dispatch({
        type: `${namespace}/getPriceRatio`,
        payload: {}
      })
    }
    form.resetFields()
  }
  //区域改变时
  function inputAreaChange(value, name) {
    if(name =='regionCode'&&value == undefined){
      value = ""
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        query: {
          ...query,
          [name]: value,
        }
      }
    })
    if(name == 'areaCode'){
      dispatch({
        type: `${namespace}/findByCity`,
        payload: {areaId:value}
      })
    }
    if(name == 'cityCode'){
      dispatch({
        type: `${namespace}/getCountyList`,
        payload: {cityid:value}
      })
    }
  }
  function submit(){
    validateFieldsAndScroll((err) => {
      if (err) {
        return false
      } else {
        dispatch({
          type: `${namespace}/submit`,
          payload: {}
        })
      }
    })
  }
  function queryMonthList(){
    validateFieldsAndScroll((err) => {
      if (err) {
        return false
      } else {
        dispatch({
          type: `${namespace}/queryMonthList`,
          payload: {}
        })
      }
    })
  }
  return (
    <div className='public_listMain'>
      <div className={"functionButton"}>
        <Button disabled={actionType == 'check'} type='primary' onClick={e => submit()} loading={btnLoading}>提交</Button>
      </div>

      <CollapsiblePanels title="市场月报信息" hideUpDownBtn={true} >
        <Row>
          <Col span={8}>
            <FormItem label='统计月份'  {...formItemLayoutPro}>
              {getFieldDecorator('month', {
                rules: [{
                  required: true, message: '注：所选月份已存在数据，请重新选择月份'
                }],
                initialValue: query.month ? moment(query.month, 'YYYY-MM-DD') : null
              })(
                <MonthPicker disabled={actionType == 'check'} onChange={(e,val) => { inputChange(val, 'month') }} placeholder="请选择统计月份" />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='区域'  {...formItemLayoutPro}>
              {getFieldDecorator('areaCode', {
                rules: [{
                  required: true, whitespace: true, message: '请选择区域'
                }],
                initialValue: query.areaCode
              })(
                <Select disabled={actionType == 'check'} placeholder='请选择区域' onChange={(e) => { inputAreaChange(e, 'areaCode') }}>
                    {areaList == undefined ?null:areaList.map((item)=>{
                      return <Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
                    })}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='城市'  {...formItemLayoutPro}>
              {getFieldDecorator('cityCode', {
                rules: [{
                  required: true, whitespace: true, message: '请选择城市'
                }],
                initialValue: query.cityCode
              })(
                <Select disabled={actionType == 'check'} placeholder='请选择城市' onChange={(e) => { inputAreaChange(e, 'cityCode') }}>
                 {cityList == undefined ?null:cityList.map((item)=>{
                    return <Select.Option key={item.cityid} value={item.cityid}>{item.city}</Select.Option>
                  })}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='县/区'  {...formItemLayoutPro}>
              {getFieldDecorator('regionCode', {
                rules: [{
                  required: false, whitespace: true, message: '请选择县/区'
                }],
                initialValue: query.regionCode
              })(
                <Select allowClear={true} disabled={actionType == 'check'} placeholder='请选择县/区' onChange={(e) => { inputAreaChange(e, 'regionCode') }}>
                 {countyList == undefined ?null:countyList.map((item)=>{
                    return <Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
                  })}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='新供面积（m²）'  {...formItemLayoutPro}>
              {getFieldDecorator('addAcreage', {
                rules: [{
                  required: true, whitespace: true, message: '请输入新供面积',
                },{ pattern: /^[+-]?\d*\.?\d*$/, message: '请输入数字' }],
                initialValue: query.addAcreage+''
              })(
                <Input disabled={actionType == 'check'} placeholder='请输入新供面积'  onChange={(e) => { inputChange(e.target.value, 'addAcreage') }} />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='成交面积（m²）'  {...formItemLayoutPro}>
              {getFieldDecorator('transactionAcreage', {
                rules: [{
                  required: true, whitespace: true, message: '请输入成交面积'
                },{ pattern: /^[+-]?\d*\.?\d*$/, message: '请输入数字' }],
                initialValue: query.transactionAcreage+''
              })(
                <Input disabled={actionType == 'check'} placeholder='请输入成交面积'  onChange={(e) => { inputChange(e.target.value, 'transactionAcreage') }} />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='成交均价（元/m²）'  {...formItemLayoutPro}>
              {getFieldDecorator('averagePrice', {
                rules: [{
                  required: true, whitespace: true, message: '请输入成交均价'
                },{ pattern: /^[+-]?\d*\.?\d*$/, message: '请输入数字' }],
                initialValue: query.averagePrice+''
              })(
                <Input disabled={actionType == 'check'} placeholder='请输入成交均价' onChange={(e) => { inputChange(e.target.value, 'averagePrice') }} />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='销售金额（元）'  {...formItemLayoutPro}>
              {getFieldDecorator('salesAmount', {
                rules: [{
                  required: true, whitespace: true, message: '请输入销售金额'
                },{ pattern: /^[+-]?\d*\.?\d*$/, message: '请输入数字' }],
                initialValue: query.salesAmount+''
              })(
                <Input disabled={true} placeholder='请输入销售金额'  onChange={(e) => { inputChange(e.target.value, 'salesAmount') }} />
              )}
            </FormItem>
            <Tooltip
                  title={'销售全额=成交面积*成交均价'}
              >
                <Icon style={{color:'#0877fd',fontSize:'18px',position: 'absolute',right: '10%',top: '15px',zIndex: 9}} type="question-circle" />
            </Tooltip>
          </Col>
        </Row>
          <Row>
          <Col span={8}>
            <FormItem label='数据来源'  {...formItemLayoutPro}>
              {getFieldDecorator('dataSources', {
                rules: [{
                  required: true, whitespace: true, message: '请输入数据来源'
                }],
                initialValue: query.dataSources
              })(
                <Input disabled={actionType == 'check'} placeholder='请输入数据来源'  onChange={(e) => { inputChange(e.target.value, 'dataSources') }} />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='面积环比（%）'  {...formItemLayoutPro}>
              {getFieldDecorator('acreageRatio', {
                rules: [{
                  required: true, whitespace: true, message: '请输入面积环比'
                },{ pattern: /^[+-]?\d*\.?\d*$/, message: '请输入数字' }],
                initialValue: query.acreageRatio+''
              })(
                <Input disabled={true} placeholder='请输入面积环比'  onChange={(e) => { inputChange(e.target.value, 'acreageRatio') }} />
              )}
            </FormItem>
            <Tooltip
                  title={'面积环比={（上个月面积-上上月面积）/上上月面积}*100%'}
              >
                <Icon style={{color:'#0877fd',fontSize:'18px',position: 'absolute',right: '10%',top: '15px',zIndex: 9}} type="question-circle" />
            </Tooltip>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='均价环比（%）'  {...formItemLayoutPro}>
              {getFieldDecorator('averageRatio', {
                rules: [{
                  required: true, whitespace: true, message: '请输入均价环比'
               },{ pattern: /^[+-]?\d*\.?\d*$/, message: '请输入数字' }],
                initialValue: query.averageRatio+''
              })(
                <Input disabled={true} placeholder='请输入均价环比' onChange={(e) => { inputChange(e.target.value, 'averageRatio') }} />
              )}
            </FormItem>
            <Tooltip
                  title={'均价环比={（上个月均价-上上月均价）/上上月均价}*100%'}
              >
                <Icon style={{color:'#0877fd',fontSize:'18px',position: 'absolute',right: '10%',top: '15px',zIndex: 9}} type="question-circle" />
            </Tooltip>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='量价情况'  {...formItemLayoutPro}>
              {getFieldDecorator('quantityRatio', {
                rules: [{
                  required: true, whitespace: true, message: '请输入量价情况'
                }],
                initialValue: query.quantityRatio+''
              })(
                <Input disabled={true} placeholder='请输入量价情况'  onChange={(e) => { inputChange(e.target.value, 'quantityRatio') }} />
              )}
            </FormItem>
            <Tooltip
                  title={'1.量价齐升：面积环比和均价环比≥3%;2.量升价平跌：面积环比≥3%，均价环比<3%;3.量平价平/跌：-3%<面积环比<3%,均价环比≥3%或均价环比≤-3%;4.量平齐平：-3%<面积环比<3%,-3%<均价环比<均价3%;5.量价齐跌：面积环比和均价环比≤-3%;6.量跌价升/平：面积环比≤-3%，均价环比>-3%'}
              >
                <Icon style={{color:'#0877fd',fontSize:'18px',position: 'absolute',right: '10%',top: '15px',zIndex: 9}} type="question-circle" />
            </Tooltip>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
          <FormItem {...formItemLayoutPro}
              label="理由说明">
              {getFieldDecorator('reason', {
                initialValue: query.reason,
                rules: [
                  { required: true, whitespace: true, message: '请输入理由说明', },
                ],
              })(
              <TextArea disabled={actionType == 'check'} placeholder='请输入理由说明' style={{width:500}} onChange={e=>{inputChange(e.target.value,'reason')}}></TextArea>
              )}
            </FormItem>
          </Col>
        </Row>
      </CollapsiblePanels>
      <div style={{padding:'0 16px'}}>
          <div style={{padding:'12px'}}>
            市场走势图 :  <a  onClick={e => queryMonthList()}>点击获取</a>
          </div>
          {tableData.length>0&&<Row>
             <Col span={11}>
             {optionData.yuefen.length&&<ReactEcharts style={{border: '1px solid #e5e5e5'}} option={option}></ReactEcharts>}
             </Col>
             <Col span={1}></Col>
             <Col span={12}>
                <Grid {...gridProps}/>
             </Col>
          </Row>}
      </div>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(monthReportDetailView))